import React, { useMemo, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Tag,
  Space,
  Modal,
  Switch,
  Tabs,
  message,
} from 'antd';
import {
  HddOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SwapOutlined,
  SettingOutlined,
} from '@ant-design/icons';

// 机器设置拆分组件（对齐 merchant-end-111/src/views/machine/components）
import BasicSetting from './components/BasicSetting';
import PaySetting from './components/PaySetting';
import PlaySetting from './components/PlaySetting';
import WakeupSetting from './components/WakeupSetting';
import ScreenSetting from './components/ScreenSetting';
import ShootSetting from './components/ShootSetting';
import UvSetting from './components/UvSetting';
import UvRoad from './components/UvRoad';

const { Option } = Select;

export default function DeviceList() {
  const [form] = Form.useForm();
  const [data, setData] = useState(() => (
    Array.from({ length: 12 }).map((_, i) => ({
      id: i + 1,
      deviceNo: `D-${1000 + i}`,
      deviceName: `设备-${i + 1}`,
      businessAccount: i % 2 === 0 ? 'merchant_A' : 'merchant_B',
      machineNo: `M-${2000 + i}`,
      systemNo: `SYS-${3000 + i}`,
      isOnline: i % 3 !== 0,
      location: i % 2 === 0 ? '上海' : '北京',
      createTime: `2025-01-${(i % 28) + 1} 10:00:00`,
      printCount: Math.floor(Math.random() * 100),
      photoCount: Math.floor(Math.random() * 200),
    }))
  ));
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [editOpen, setEditOpen] = useState(false);
  const [transferOpen, setTransferOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [settingsRow, setSettingsRow] = useState(null);
  const [settingsForm] = Form.useForm();

  const columns = useMemo(() => ([
    { title: '设备编号', dataIndex: 'deviceNo', width: 140 },
    { title: '设备名称', dataIndex: 'deviceName', width: 140 },
    {
      title: '在线状态',
      dataIndex: 'isOnline',
      width: 110,
      render: (val) => val ? <Tag color="green">在线</Tag> : <Tag color="red">离线</Tag>,
    },
    { title: '商家账号', dataIndex: 'businessAccount', width: 160 },
    { title: '机器编号', dataIndex: 'machineNo', width: 140 },
    { title: '系统编号', dataIndex: 'systemNo', width: 160 },
    { title: '所在地', dataIndex: 'location', width: 120 },
    { title: '创建时间', dataIndex: 'createTime', width: 180 },
    { title: '打印次数', dataIndex: 'printCount', width: 100 },
    { title: '拍照次数', dataIndex: 'photoCount', width: 100 },
    {
      title: '操作',
      dataIndex: 'actions',
      fixed: 'right',
      align: 'right',
      width: 280,
      render: (_, row) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(row)}>编辑</Button>
          <Button size="small" icon={<SwapOutlined />} onClick={() => handleTransfer(row)}>转移</Button>
          <Button size="small" icon={<SettingOutlined />} onClick={() => openSettings(row)}>机器设置</Button>
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(row)}>删除</Button>
        </Space>
      )
    },
  ]), []);

  const handleSearch = async () => {
    const values = await form.validateFields().catch(() => null);
    if (!values) return;
    setLoading(true);
    // Simulate filter locally
    setTimeout(() => {
      setData(prev => prev.filter(item => {
        const byAcc = values.businessAccount ? item.businessAccount.includes(values.businessAccount) : true;
        const byName = values.deviceName ? item.deviceName.includes(values.deviceName) : true;
        const byNo = values.deviceNo ? item.deviceNo.includes(values.deviceNo) : true;
        const bySys = values.systemNo ? item.systemNo.includes(values.systemNo) : true;
        const byOnline = values.online === undefined ? true : item.isOnline === (values.online === '1');
        return byAcc && byName && byNo && bySys && byOnline;
      }));
      setLoading(false);
    }, 300);
  };

  const resetSearch = () => {
    form.resetFields();
    // Restore initial data
    setData(Array.from({ length: 12 }).map((_, i) => ({
      id: i + 1,
      deviceNo: `D-${1000 + i}`,
      deviceName: `设备-${i + 1}`,
      businessAccount: i % 2 === 0 ? 'merchant_A' : 'merchant_B',
      machineNo: `M-${2000 + i}`,
      systemNo: `SYS-${3000 + i}`,
      isOnline: i % 3 !== 0,
      location: i % 2 === 0 ? '上海' : '北京',
      createTime: `2025-01-${(i % 28) + 1} 10:00:00`,
      printCount: Math.floor(Math.random() * 100),
      photoCount: Math.floor(Math.random() * 200),
    })));
  };

  const handleEdit = (row) => {
    setCurrentRow(row);
    setEditOpen(true);
  };
  const handleTransfer = (row) => {
    setCurrentRow(row);
    setTransferOpen(true);
  };
  const handleDelete = (row) => {
    Modal.confirm({
      title: '确认删除',
      content: `将删除设备 ${row.deviceName}（${row.deviceNo}）`,
      onOk: () => {
        setData(prev => prev.filter(d => d.id !== row.id));
        message.success('删除成功');
      },
    });
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const addDevice = () => {
    setCurrentRow(null);
    setEditOpen(true);
  };

  const handleEditSubmit = (values) => {
    if (currentRow) {
      setData(prev => prev.map(d => (d.id === currentRow.id ? { ...d, ...values } : d)));
      message.success('编辑成功');
    } else {
      const newId = Math.max(...data.map(d => d.id)) + 1;
      setData(prev => [{
        id: newId,
        deviceNo: values.deviceNo || `D-${1000 + newId}`,
        deviceName: values.deviceName || `新设备-${newId}`,
        businessAccount: values.businessAccount || 'merchant_A',
        machineNo: values.machineNo || `M-${2000 + newId}`,
        systemNo: values.systemNo || `SYS-${3000 + newId}`,
        isOnline: true,
        location: values.location || '上海',
        createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
        printCount: 0,
        photoCount: 0,
      }, ...prev]);
      message.success('新增成功');
    }
    setEditOpen(false);
  };

  const handleTransferSubmit = (values) => {
    message.success(`设备已转移到 ${values.toBusiness || '目标商家'}`);
    setTransferOpen(false);
  };

  const openSettings = (row) => {
    setSettingsRow(row);
    setSettingsOpen(true);
  };

  const handleSettingsSubmit = async () => {
    try {
      const values = await settingsForm.validateFields();
      setData(prev => prev.map(d => (
        d.id === settingsRow.id
          ? {
              ...d,
              deviceName: values.deviceName ?? d.deviceName,
              location: values.location ?? d.location,
              isOnline: typeof values.isOnline === 'boolean' ? values.isOnline : d.isOnline,
              machineSettings: {
                currencySymbol: values.currencySymbol ?? (d.machineSettings?.currencySymbol ?? '￥'),
                gameplayEnabled: typeof values.gameplayEnabled === 'boolean' ? values.gameplayEnabled : (d.machineSettings?.gameplayEnabled ?? true),
                consumableLowReminder: values.consumableLowReminder ?? (d.machineSettings?.consumableLowReminder ?? ''),
                theme: values.theme ?? (d.machineSettings?.theme ?? 'default'),
                resolution: values.resolution ?? (d.machineSettings?.resolution ?? '1080p'),
                uvEnabled: typeof values.uvEnabled === 'boolean' ? values.uvEnabled : (d.machineSettings?.uvEnabled ?? false),
                machineFunction: values.machineFunction ?? (d.machineSettings?.machineFunction ?? []),
                machineScreenDirection: values.machineScreenDirection ?? (d.machineSettings?.machineScreenDirection ?? 'portrait'),
                templateCustomConfig: values.templateCustomConfig ?? d.machineSettings?.templateCustomConfig,
                homePageCustomConfig: values.homePageCustomConfig ?? d.machineSettings?.homePageCustomConfig,
                insCustomConfig: values.insCustomConfig ?? d.machineSettings?.insCustomConfig,
                insEditCustomConfig: values.insEditCustomConfig ?? d.machineSettings?.insEditCustomConfig,
                aiTemplateCustomConfig: values.aiTemplateCustomConfig ?? d.machineSettings?.aiTemplateCustomConfig,
                scanCodeUploadCustomConfig: values.scanCodeUploadCustomConfig ?? d.machineSettings?.scanCodeUploadCustomConfig,
                printPreviewCustomConfig: values.printPreviewCustomConfig ?? d.machineSettings?.printPreviewCustomConfig,
              }
            }
          : d
      )));
      message.success('机器设置已保存');
      setSettingsOpen(false);
    } catch (e) {
      // 校验未通过或其它异常
    }
  };

  return (
    <div style={{ padding: 16 }}>
      <Card
        title={<Space><HddOutlined />设备管理 - 设备列表</Space>}
        extra={(
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={addDevice}>新增设备</Button>
            <Button danger disabled={!selectedRowKeys.length} onClick={() => {
              Modal.confirm({
                title: '批量删除',
                content: `确定删除选中的 ${selectedRowKeys.length} 台设备？`,
                onOk: () => {
                  setData(prev => prev.filter(d => !selectedRowKeys.includes(d.id)));
                  setSelectedRowKeys([]);
                  message.success('批量删除成功');
                },
              });
            }}>批量删除</Button>
          </Space>
        )}
        style={{ marginBottom: 16 }}
      >
        <Form
          layout="inline"
          form={form}
          onFinish={handleEditSubmit}
          style={{ rowGap: 12 }}
        >
          <Form.Item name="businessAccount" label="商家账号">
            <Input placeholder="请输入商家账号" allowClear />
          </Form.Item>
          <Form.Item name="deviceName" label="设备名称">
            <Input placeholder="请输入设备名称" allowClear />
          </Form.Item>
          <Form.Item name="deviceNo" label="设备编号">
            <Input placeholder="请输入设备编号" allowClear />
          </Form.Item>
          <Form.Item name="systemNo" label="系统编号">
            <Input placeholder="请输入系统编号" allowClear />
          </Form.Item>
          <Form.Item name="online" label="在线状态">
            <Select allowClear placeholder="全部" style={{ width: 120 }}>
              <Option value="1">在线</Option>
              <Option value="0">离线</Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" onClick={handleSearch}>查询</Button>
              <Button onClick={resetSearch}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          rowSelection={rowSelection}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 编辑/新增 */}
      <Modal
        title={currentRow ? '编辑设备' : '新增设备'}
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        onOk={() => {
          const formId = 'device-edit-form';
          const formEl = document.getElementById(formId);
          if (formEl) {
            const values = Object.fromEntries(new FormData(formEl).entries());
            handleEditSubmit(values);
          }
        }}
        destroyOnClose
      >
        <form id="device-edit-form">
          <Space direction="vertical" style={{ width: '100%' }}>
            <Input name="deviceName" defaultValue={currentRow?.deviceName} placeholder="设备名称" />
            <Input name="deviceNo" defaultValue={currentRow?.deviceNo} placeholder="设备编号" />
            <Input name="businessAccount" defaultValue={currentRow?.businessAccount} placeholder="商家账号" />
            <Input name="machineNo" defaultValue={currentRow?.machineNo} placeholder="机器编号" />
            <Input name="systemNo" defaultValue={currentRow?.systemNo} placeholder="系统编号" />
            <Input name="location" defaultValue={currentRow?.location} placeholder="所在地" />
            <Space>
              在线：<Switch defaultChecked={currentRow ? currentRow.isOnline : true} />
            </Space>
          </Space>
        </form>
      </Modal>

      {/* 转移 */}
      <Modal
        title="设备转移"
        open={transferOpen}
        onCancel={() => setTransferOpen(false)}
        onOk={() => {
          const formId = 'device-transfer-form';
          const formEl = document.getElementById(formId);
          if (formEl) {
            const values = Object.fromEntries(new FormData(formEl).entries());
            handleTransferSubmit(values);
          }
        }}
        destroyOnClose
      >
        <form id="device-transfer-form">
          <Space direction="vertical" style={{ width: '100%' }}>
            <Select defaultValue="1" style={{ width: '100%' }}>
              <Option value="1">永久转移</Option>
              <Option value="2">临时转移</Option>
              <Option value="3">解除转移</Option>
            </Select>
            <Input name="toBusiness" placeholder="目标商家账号/ID" />
          </Space>
        </form>
      </Modal>

      {/* 机器设置 */}
      <Modal
        title="机器设置"
        open={settingsOpen}
        onCancel={() => setSettingsOpen(false)}
        onOk={handleSettingsSubmit}
        destroyOnClose
        width={800}
      >
        <Form
          form={settingsForm}
          id="machine-settings-form"
          initialValues={{
            deviceName: settingsRow?.deviceName,
            location: settingsRow?.location,
            isOnline: settingsRow ? settingsRow.isOnline : true,
            currencySymbol: settingsRow?.machineSettings?.currencySymbol ?? '￥',
            gameplayEnabled: settingsRow?.machineSettings?.gameplayEnabled ?? true,
            consumableLowReminder: settingsRow?.machineSettings?.consumableLowReminder ?? undefined,
            theme: settingsRow?.machineSettings?.theme ?? 'default',
            resolution: settingsRow?.machineSettings?.resolution ?? '1080p',
            uvEnabled: settingsRow?.machineSettings?.uvEnabled ?? false,
            machineFunction: settingsRow?.machineSettings?.machineFunction ?? ['1','3'],
            machineScreenDirection: settingsRow?.machineSettings?.machineScreenDirection ?? 'portrait',
            templateCustomConfig: settingsRow?.machineSettings?.templateCustomConfig,
            homePageCustomConfig: settingsRow?.machineSettings?.homePageCustomConfig,
            insCustomConfig: settingsRow?.machineSettings?.insCustomConfig,
            insEditCustomConfig: settingsRow?.machineSettings?.insEditCustomConfig,
            aiTemplateCustomConfig: settingsRow?.machineSettings?.aiTemplateCustomConfig,
            scanCodeUploadCustomConfig: settingsRow?.machineSettings?.scanCodeUploadCustomConfig,
            printPreviewCustomConfig: settingsRow?.machineSettings?.printPreviewCustomConfig,
          }}
        >
          <Tabs
            defaultActiveKey="basic"
            items={[
              { key: 'basic', label: '基础设置', children: <BasicSetting /> },
              { key: 'pay', label: '收费设置', children: <PaySetting /> },
              { key: 'play', label: '玩法设置', children: <PlaySetting /> },
              { key: 'reminder', label: '提醒设置', children: <WakeupSetting /> },
              { key: 'screen', label: '界面设置', children: <ScreenSetting form={settingsForm} /> },
              { key: 'shoot', label: '拍摄设置', children: <ShootSetting /> },
              { key: 'uv', label: 'UV设置', children: <UvSetting /> },
              // 预留：根据软件版本动态展示 UV 货道设置
              // { key: 'uv-road', label: 'UV货道设置', children: <UvRoad /> },
            ]}
          />
        </Form>
      </Modal>
    </div>
  );
}